package pl.edu.uj.tcs.hkextended;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.util.Xml;

public class GoogleXMLParser implements XMLParser {

	@Override
	public Collection<SuggestItem> parse(String xml) {
		final List<SuggestItem> items = new LinkedList<SuggestItem>();
		final SuggestItem current = new SuggestItem();
		
		RootElement root = new RootElement("toplevel");
		
		Element completeSuggestion = root.getChild("CompleteSuggestion");
		completeSuggestion.setEndElementListener(new EndElementListener() {
			@Override
			public void end() {
				items.add(current);
			}
		});
		
		completeSuggestion.getChild("suggestion").setStartElementListener(new StartElementListener() {
			@Override
			public void start(Attributes arg0) {
				current.setSuggest(arg0.getValue(0));
			}
		});
		
		completeSuggestion.getChild("num_queries").setStartElementListener(new StartElementListener() {
			@Override
			public void start(Attributes arg0) {
				current.setPriority(Integer.parseInt(arg0.getValue(0)));
			}
		});
		
		try {
			Xml.parse(xml, root.getContentHandler());
		} catch (SAXException e) {
			e.printStackTrace();
		}
		
		return items;
	}

}
